package com.baor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.AccountTransactionsDao;
import com.baor.domain.*;
import com.baor.service.AccountTransactionsService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AccountTransactionServiceImpl implements AccountTransactionsService {

    @Autowired
    private AccountTransactionsDao accountTransactionsDao;

    @Override
    public R transactions(Map<String, Object> params) {
        try {
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);

            MPJLambdaWrapper<AccountTransactionsVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(AccountTransactionsVO.class)
                    .select(WorkorderVO::getUserId, WorkorderVO::getPaymentTime, WorkorderVO::getAmount, WorkorderVO::getAuditorId)
                    .select(CustomerVO::getNickname, CustomerVO::getPhone)
                    .select(UserVO::getUsername)
                    .leftJoin(WorkorderVO.class, WorkorderVO::getId, AccountTransactionsVO::getWithdrawalRecordId)
                    .leftJoin(CustomerVO.class, CustomerVO::getId, WorkorderVO::getUserId)
                    .leftJoin(UserVO.class, UserVO::getId, WorkorderVO::getAuditorId)
                .orderByDesc(WorkorderVO::getApplyTime);

            // 新增查询条件
            if (params.get("nickname") != null && !params.get("nickname").toString().trim().isEmpty()) {
                wrapper.like(CustomerVO::getNickname, params.get("nickname").toString().trim());
            }
            // 手机号搜索
            if (params.get("phone") != null && !params.get("phone").toString().trim().isEmpty()) {
                wrapper.like(CustomerVO::getPhone, params.get("phone").toString().trim());
            }
            // 交易类型过滤
            if (params.get("user_type") != null && !params.get("user_type").toString().trim().isEmpty()) {
                wrapper.eq(AccountTransactionsVO::getUserType, params.get("user_type").toString().trim());
            }
            //操作人
            if (params.get("username") != null && !params.get("username").toString().trim().isEmpty()) {
                wrapper.like(UserVO::getUsername, params.get("username").toString().trim());
            }
            if (params.get("type") != null && !params.get("type").toString().trim().isEmpty()) {
                wrapper.eq(AccountTransactionsVO::getType, params.get("type").toString().trim());
            }
            // 支付平台过滤
            if (params.get("paymentPlatform") != null && !params.get("paymentPlatform").toString().trim().isEmpty()) {
                wrapper.eq(AccountTransactionsVO::getPaymentPlatform, params.get("paymentPlatform").toString().trim());
            }
            // 时间范围过滤
            if (params.get("startTime") != null && !params.get("startTime").toString().trim().isEmpty()) {
                wrapper.ge(WorkorderVO::getPaymentTime, params.get("startTime").toString().trim());
            }
            if (params.get("endTime") != null && !params.get("endTime").toString().trim().isEmpty()) {
                wrapper.le(WorkorderVO::getPaymentTime, params.get("endTime").toString().trim());
            }
            // 用户昵称/手机号搜索
            if (params.get("keyword") != null && !params.get("keyword").toString().trim().isEmpty()) {
                String keyword = params.get("keyword").toString().trim();
                wrapper.nested(wq -> wq
                        .like(CustomerVO::getNickname, keyword)
                        .or()
                        .like(CustomerVO::getPhone, keyword)
                );
            }

             IPage<Map<String, Object>> resultPage = accountTransactionsDao.selectJoinMapsPage(page, wrapper);

            List<Map<String, Object>> resultList = resultPage.getRecords().stream()
                    .map(this::convertToFrontendFormat)
                    .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("list", resultList);
            result.put("totalSize", resultPage.getTotal());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);

            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询账户流水失败: " + e.getMessage());
        }
    }

//    private Map<String, Object> convertToFrontendFormat(Map<String, Object> record) {
//        Map<String, Object> item = new HashMap<>();
//        // 关联表字段
//        item.put("id", record.get("id"));
//        item.put("system_balance", record.get("system_balance"));
//        item.put("type", record.get("type"));
//        item.put("payment_platform", record.get("payment_platform"));
//        item.put("payment_time", record.get("payment_time"));
//        item.put("amount", record.get("amount"));
//        item.put("nickname", record.get("nickname"));
//        item.put("phone", record.get("phone"));
//        item.put("user_type", record.get("user_type"));
//        item.put("username", record.get("username"));
//
//        return item;
//    }

    private Map<String, Object> convertToFrontendFormat(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("id", record.get("id"));
        item.put("system_balance", record.get("system_balance"));
        item.put("type", record.get("type"));
        // 转换交易类型为中文显示
        item.put("type_desc", convertTransactionType((String) record.get("type")));
        item.put("payment_platform", record.get("payment_platform"));
        item.put("payment_time", record.get("payment_time"));
        item.put("amount", record.get("amount"));
        item.put("nickname", record.get("nickname"));
        item.put("phone", record.get("phone"));
        item.put("user_type", record.get("user_type"));
        // 转换用户类型为中文显示
//        item.put("user_type", convertUserType((Integer) record.get("user_type")));
        item.put("username", record.get("username"));
        // 补充收款人ID字段
        item.put("payee_id", record.get("payeeId"));
        // 补充提现记录ID字段
//        item.put("withdrawal_record_id", record.get("withdrawalRecordId"));

        return item;
    }

    /**
     * 转换交易类型为中文描述
     */
    private String convertTransactionType(String type) {
        if (type == null) return "未知";
        switch (type) {
            case "recharge": return "充值";
            case "withdraw": return "提现";
            case "reward": return "奖励";
            case "penalty": return "处罚";
            default: return "其他";
        }
    }

    /**
     * 转换用户类型为中文描述
     */
//    private String convertUserType(Integer userType) {
//        if (userType == null) return "未知";
//        switch (userType) {
//            case 1: return "管理员";
//            case 2: return "设备持有者";
//            case 3: return "未知";
//            default: return "普通用户";
//        }
//    }
}
